import { SECRET } from '@/constants/secret';
import { IS_PUBLIC_KEY } from '@/decorators/public.decorator';
import { AccessTokenData } from '@/vos/token.vo';
import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private jwtService: JwtService,
    private reflector: Reflector,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (isPublic) {
      return true;
    }
    const request = context.switchToHttp().getRequest();
    try {
      const token = request.headers.authorization?.replace('Bearer ', '');
      const payload = await this.jwtService.verifyAsync<AccessTokenData>(
        token,
        {
          secret: SECRET,
        },
      );
      request['userId'] = payload.id;
    } catch (error) {
      throw new UnauthorizedException('登录状态过期！');
    }
    return true;
  }
}
